package com.zwq.poker.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import com.zwq.common.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/feishu")
public class FeishuController {

    private String appId = "cli_a8abcd39999fd00b";

    private String appSecret = "4RoUNEZ4jJFf5Hoto8eRifRELZFZHIFW";


    @RequestMapping("/token")
    public String getToken() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
        HashMap<String, Object> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("app_secret", appSecret);
        String s = restTemplate.postForObject(url, params, String.class);
        JSONObject jsonObject = JSON.parseObject(s);
        return jsonObject.getString("tenant_access_token");
    }


    @GetMapping("/send")
    public ResponseResult<String> sendMessage(@RequestParam("message") String message) throws Exception {

        // 构建client
        Client client = Client.newBuilder(appId, appSecret).build();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", message);


        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("chat_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId("oc_b75088925a206ce7a21d6c7055cef60b")
                        .msgType("text")
                        .content(jsonObject.toJSONString())
                        .uuid(UUID.randomUUID().toString())
                        .build()
                ).build();

        RequestOptions requestOptions = RequestOptions.newBuilder().tenantAccessToken(getToken()).build();

        // 发起请求
        CreateMessageResp resp = client.im().v1().message().create(req, requestOptions);

        // 处理服务端错误
        if (!resp.success()) {
            String errorMessage = String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8))));
            ResponseResult.success(errorMessage);
        }

        // 业务数据处理
        return ResponseResult.success(Jsons.DEFAULT.toJson(resp.getData()));
    }


}
